package cn.daichi.redisidempotency.interceptor;

import cn.daichi.redisidempotency.annotation.Idempotency;
import cn.daichi.redisidempotency.service.IdempotencyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class IdempotencyInterceptor implements HandlerInterceptor {

    private final IdempotencyService idempotencyService;

    public IdempotencyInterceptor(IdempotencyService idempotencyService) {
        this.idempotencyService = idempotencyService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //获取到方法
        Method method = handlerMethod.getMethod();
        //被@Idempotent注解标记的扫描
        Idempotency methodAnnotation = method.getAnnotation(Idempotency.class);
        if (methodAnnotation != null) {
            // 幂等性校验, 校验通过则放行, 校验失败则抛出异常
            idempotencyService.checkIdempotency(request);
        }
        return true;
    }


}
